<template>
    <div class="camera_outer flex flex-row items-center">
        <div class="button flex flex-col items-center mx-10px">
            <div class="" @click="getCompetence">
                <img class="w-50px h50px" src="./../assets/pictures.png" alt="">
                <span v-show="!cameraOption.thisVideoIsShow" class="text-light-blue-500">Clock In</span>
            </div>
            <button v-show="cameraOption.thisVideoIsShow" @click="setImage">拍照</button>
            <!-- <button @click="stopNavigator()">关闭摄像头</button> -->
        </div>
        <div class="camera_inner relative">
            <div class="loading absolute left-20px top-0" v-show="cameraOption.loading">
                <img src="./../assets/loading.png" alt="">
            </div>
            <video 
                id="videoCamera" 
                v-show="cameraOption.thisVideoIsShow" 
                :width="cameraOption.videoWidth" 
                :height="cameraOption.videoHeight" autoplay>
            </video>
            <canvas 
                class="hidden" 
                id="canvasCamera" 
                :width="cameraOption.videoWidth" 
                :height="cameraOption.videoHeight">
            </canvas>
            <div 
                class="img_bg_camera" 
                v-if="cameraOption.imgSrc && !cameraOption.thisVideoIsShow">
                <img :src="cameraOption.imgSrc" class="tx_img" />
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { clockInApi, uploadApi } from '@/api/index.js'
import { isCurrentTimeInSlot } from '@/utils/index.ts'

const props = defineProps({
    modelValue:{
        type: Boolean,
        required:true
    },
    getClockInfo:{
        type: Function
    }
})
const emits = defineEmits(['update:modelValue'])

const cameraOption = reactive({
    videoWidth: 100,
    videoHeight: 100,
    imgSrc: "",
    thisCancas: null,
    thisContext: null,
    thisVideo: null,// video摄像头容器
    thisVideoIsShow:false,// 摄像头是否渲染
    loading:false,// 加载动效
    openVideo: false,
})

// 调用权限（打开摄像头功能）
const getCompetence = () => {
    if(!isCurrentTimeInSlot()){
        alert('哥哥, 现在还不是打卡时间段哦, 给我等会再来!')
        return
    }
      // 判断是否登录:输入姓名 + 选择班级
    const userInfo = localStorage.getItem('userInfo')
    if(!userInfo){// 未登录
        emits("update:modelValue",true)
        return
    }else{
        emits("update:modelValue",false)
    }

    cameraOption.thisCancas = document.getElementById("canvasCamera");
    cameraOption.thisContext = cameraOption.thisCancas?.getContext("2d");
    cameraOption.thisVideo = document.getElementById("videoCamera");
    // cameraOption.thisVideo.style.display = "block";
    cameraOption.thisVideoIsShow = true
    cameraOption.loading = true

    // 获取媒体属性，旧版本浏览器可能不支持mediaDevices，我们首先设置一个空对象
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }
    // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
    // 使用getUserMedia，因为它会覆盖现有的属性。
    // 这里，如果缺少getUserMedia属性，就添加它。
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            var getUserMedia =
                navigator.webkitGetUserMedia ||
                navigator.mozGetUserMedia ||
                navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
                //不存在则报错
                return Promise.reject(
                    new Error("getUserMedia is not implemented in this browser")
                );
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
            });
        };
    }
    var constraints = {
        audio: false,
        video: {
            width: cameraOption.videoWidth,
            height: cameraOption.videoHeight,
            transform: "scaleX(-1)",
        },
    };
    navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in cameraOption.thisVideo) {
                cameraOption.thisVideo.srcObject = stream;
            } else {
                // 避免在新的浏览器中使用它，因为它正在被弃用。
                cameraOption.thisVideo.src = window.URL.createObjectURL(stream);
            }
            cameraOption.thisVideo.onloadedmetadata = function (e) {
                cameraOption.thisVideo?.play();
            };
        })
        .catch((err) => {
            console.log(err);
        });
    setTimeout(() => {
        cameraOption.loading = false
    }, 300);
    // alert("打开摄像头");
}

//  绘制图片（拍照功能）
const setImage = () => {
    var _this = this;
    // canvas画图
    cameraOption.thisContext.drawImage(
        cameraOption.thisVideo,
        0,
        0,
        cameraOption.videoWidth,
        cameraOption.videoHeight
    );
    // 获取图片base64链接
    var image = cameraOption.thisCancas.toDataURL("image/png");
    cameraOption.imgSrc = image; //赋值并预览图片
    // alert("拍照");

    const { user_id, department_id, department } = JSON.parse(localStorage.getItem('userInfo'))
    // 1.上传图片, 上传成功后再插入打卡记录
    uploadApi({department, user_id, url:image}).then((res_pic)=>{
        console.log(res_pic);
        if(res_pic.code==200){
            // 2.插入打卡记录,需要判断时间段,才能打卡
            console.log(user_id, department_id);
            clockInApi({ user_id, department_id, clock_url:res_pic.data }).then(res=>{
                console.log(res);
                props.getClockInfo()// bug呀 为啥不调用？？
                // location.reload()// 刷新页面
            })
        }
    })
    
    // 关闭摄像头
    setTimeout(() => {
        cameraOption.thisVideoIsShow = false 
        stopNavigator()
    }, 500);
}

// 拿到图片并打卡（上传到服务器）
const clockIn = () =>{

}

// 关闭摄像头
const stopNavigator = () => {
    cameraOption.thisVideo.srcObject.getTracks()[0].stop();
    // alert("关闭摄像头");
}
</script>

<style scoped>
@keyframes rotate {
    0%{
        transform: rotate(0deg);
    }
    100%{
        transform: rotate(360deg);
    }
}
.loading img{
    width: 30px;
    height: 30px;
    animation: rotate 1s linear infinite;
}
#videoCamera, .tx_img{
    border-radius: 50px;
    object-fit: cover;
}
</style>